<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="字典名称" prop="dictNameLike">
        <el-input
          v-model="queryParams.dictNameLike"
          placeholder="请输入字典名称"
          clearable
          size="default"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="字典类型" prop="dictTypeLike">
        <el-input
          v-model="queryParams.dictTypeLike"
          placeholder="请输入字典类型"
          clearable
          size="default"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="字典状态"
          clearable
          size="default"
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="修改时间">
        <el-date-picker
          v-model="dateRange"
          size="default"
          style="width: 240px"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <search-button @click="handleQuery" :perm="['system:dict:search']" />
        <reset-button @click="resetQuery" :perm="['system:dict:search']" />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <add-button @click="handleAdd" :perm="['system:dict:insert']" :roleType="['conf']" />
      <delete-button
        @click="handleDelete"
        :disabled="multiple"
        :perm="['system:dict:delete']"
        :roleType="['conf']"
      />
      <export-button @click="handleExport" :perm="['system:dict:export']" />
      <clear-button
        @click="handleClearCache"
        :perm="['system:dict:cache']"
        :roleType="['conf']"
        text="清理缓存"
      />
      <right-toolbar
        v-model:showSearch="showSearch"
        @query-table="getList"
        :perm="['system:dict:search']"
      />
    </el-row>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="字典编号" align="center" prop="dictId" width="80px" />
      <el-table-column
        label="字典名称"
        align="center"
        prop="dictName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="字典类型" align="center" :show-overflow-tooltip="true">
        <template #default="scope">
          <router-link
            :to="'/dict/type/data/' + scope.row.dictId"
            class="link-type"
            v-if="scope.row.sqlModeOn === 'N'"
          >
            <span>{{ scope.row.dictType }}</span>
          </router-link>
          <span v-else>{{ scope.row.dictType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80px">
        <template #default="scope">
          <span :class="scope.row.status === 'N' ? 'text-danger' : ''">{{
            selectDictLabel(statusOptions, scope.row.status)
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="SQL模式" align="center" prop="sqlModeOn" width="80px">
        <template #default="scope">
          <el-popover
            v-if="scope.row.sqlModeOn === 'Y'"
            placement="top-start"
            width="240"
            trigger="hover"
            title="SQL语句"
            :content="scope.row.viewSql"
          >
            <template #reference>
              <el-tag type="success">{{
                selectDictLabel(yesOrNoOptions, scope.row.sqlModeOn)
              }}</el-tag>
            </template>
          </el-popover>
          <span v-else>{{ selectDictLabel(yesOrNoOptions, scope.row.sqlModeOn) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160px" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="160px" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="160px"
        v-if="hasRoleType(['conf'])"
      >
        <template #default="scope">
          <text-edit-button
            @click="handleUpdate(scope.row)"
            :perm="['system:dict:update']"
            :roleType="['conf']"
          />
          <text-delete-button
            @click="handleDelete(scope.row)"
            :perm="['system:dict:delete']"
            :roleType="['conf']"
            :title="'是否确认删除' + scope.row.dictName + '?'"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <drag-dialog
      :title="title"
      :close-on-click-modal="false"
      v-model="open"
      width="800px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="form.dictType" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :value="dict.dictValue">{{
              dict.dictLabel
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="模式" prop="sqlModeOn">
          <el-switch
            v-model="form.sqlModeOn"
            active-text="SQL模式"
            active-value="Y"
            inactive-text="值集模式"
            inactive-value="N"
          />
        </el-form-item>
        <el-form-item label="SQL语句" prop="viewSql" v-if="form.sqlModeOn === 'Y'">
          <el-input
            v-model="form.viewSql"
            type="textarea"
            :autosize="{ minRows: 2 }"
            placeholder="请输入SQL语句"
          />
        </el-form-item>
        <el-form-item label="扩展字段" prop="extcols" v-if="form.sqlModeOn === 'N'">
          <el-row>
            <el-col :span="8" class="text-center">是否启用</el-col>
            <el-col :span="8" class="text-center required">显示名</el-col>
            <el-col :span="8" class="text-center required">字段别名</el-col>
          </el-row>
          <el-row
            class="mt5 mb8"
            v-for="extcol in extColNames"
            :key="extcol.extcolName"
            :gutter="20"
          >
            <el-col :span="8" class="text-center">
              <el-checkbox v-model="extcol.enabled" :label="extcol.extcolName">{{
                extcol.extcolName
              }}</el-checkbox>
            </el-col>
            <el-col :span="8" class="text-center">
              <el-input
                v-model="extcol.extcolLabel"
                :disabled="!extcol.enabled"
                @blur="(event) => needInputCheck(event, extcol.extcolLabel, extcol)"
              />
            </el-col>
            <el-col :span="8" class="text-center">
              <el-input
                v-model="extcol.extcolAlias"
                :disabled="!extcol.enabled"
                @blur="(event) => needInputCheck(event, extcol.extcolAlias, extcol)"
              />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" />
        </el-form-item>
      </el-form>
      <template #footer>
        <dialog-footer @ok="submitForm" @cancel="cancel" />
      </template>
    </drag-dialog>
  </div>
</template>

<script>
import {
  search,
  getType,
  delType,
  addType,
  updateType,
  checkDictTypeUnique,
  clearCache
} from '@base/api/base/dict/type'
import { buildExtColNames } from '@/utils/zmids'
import { trim } from 'lodash-es'

export default {
  name: 'SystemDict',
  data() {
    const checkDictTypeUniqueRule = (rule, value, callback) => {
      checkDictTypeUnique(value, this.form.dictId).then((response) => {
        if (response.data === true) {
          callback('字典类型已存在')
        } else {
          callback()
        }
      })
    }

    return {
      // 遮罩层
      loading: true,
      // 扩展字段配置
      extColNames: buildExtColNames(8),
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 是否字典
      yesOrNoOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderBy: 'UPDATE_TIME',
        sortDirect: 'DESC',
        dictNameLike: undefined,
        dictTypeLike: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dictName: [{ required: true, message: '字典名称不能为空', trigger: 'blur' }],
        dictType: [
          { required: true, message: '字典类型不能为空', trigger: 'blur' },
          { required: true, validator: checkDictTypeUniqueRule, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('sys_normal_disable').then((response) => {
      this.statusOptions = response.data
    })
    this.getDicts('sys_yes_no').then((response) => {
      this.yesOrNoOptions = response.data
    })
  },
  methods: {
    /** 查询字典类型列表 */
    getList() {
      this.loading = true
      search(
        this.addDateRange(this.queryParams, ['updateTimeStart', 'updateTimeEnd'], this.dateRange)
      ).then((response) => {
        this.typeList = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        dictId: undefined,
        dictName: '',
        dictType: '',
        sqlModeOn: 'N',
        status: 'Y',
        remark: '',
        extcols: undefined,
        viewSql: ''
      }
      this.extColNames = buildExtColNames(8)
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加字典类型'
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.dictId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const dictId = row.dictId || this.ids[0]
      getType(dictId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改字典类型'
        const extcols = response.data.params || {}
        for (let index = 0; index < this.extColNames.length; index++) {
          const element = this.extColNames[index]
          const extcol = extcols[element.extcolName] || {}
          element.enabled = extcol.status === 'Y'
          element.extcolLabel = extcol.extcolLabel
          element.extcolAlias = extcol.extcolAlias
        }
      })
    },
    // 显示名和别名必输校验
    needInputCheck: function (event, value, extcol) {
      if (extcol.enabled === true && (value === undefined || trim(value) == '')) {
        event.target.style.border = '1px solid red'
      } else {
        event.target.style.border = ''
      }
    },
    // 校验
    validExtCols: function () {
      const aliasUnique = {}
      const labelUnique = {}
      for (let index = 0; index < this.extColNames.length; index++) {
        const element = this.extColNames[index]
        // 启用的情况下显示名和别名不能为空
        if (element.enabled === true) {
          if (
            element.extcolLabel === undefined ||
            element.extcolLabel === 'undefined' ||
            trim(element.extcolLabel) === ''
          ) {
            this.msgError('显示名不可以为空')
            return false
          }
          if (
            element.extcolAlias === undefined ||
            element.extcolAlias === 'undefined' ||
            trim(element.extcolAlias) === ''
          ) {
            this.msgError('别名不可以为空')
            return false
          }

          if (labelUnique[element.extcolLabel] === true) {
            this.msgError('显示名[' + element.extcolLabel + ']不可以重复')
            return false
          }
          labelUnique[element.extcolLabel] = true

          if (element.extcolAlias && aliasUnique[element.extcolAlias] === true) {
            this.msgError('别名[' + element.extcolAlias + ']不可以重复')
            return false
          }
          aliasUnique[element.extcolAlias] = true
        }
      }
      return true
    },
    /** 提交按钮 */
    submitForm: function () {
      if (!this.validExtCols()) {
        return
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.extcols = []
          for (let index = 0; index < this.extColNames.length; index++) {
            const element = this.extColNames[index]
            if (element.enabled === true) {
              this.form.extcols.push({
                status: element.enabled === true ? 'Y' : 'N',
                extcolName: element.extcolName,
                extcolAlias: element.extcolAlias,
                extcolLabel: element.extcolLabel
              })
            }
          }
          if (this.form.dictId != undefined) {
            updateType(this.form).then((response) => {
              if (response.data === 1) {
                this.msgSuccess('修改成功')
                this.open = false
                this.getList()
              }
            })
          } else {
            addType(this.form).then((response) => {
              if (response.data === 1) {
                this.msgSuccess('新增成功')
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dictIds = row ? row.dictId : this.ids.join(',')
      delType(dictIds)
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(function () {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.downloadUrl(
        '/system/dict/export',
        this.addDateRange(this.queryParams, ['updateTimeStart', 'updateTimeEnd'], this.dateRange)
      )
    },
    /** 清理缓存按钮操作 */
    handleClearCache() {
      clearCache().then((res) => {
        if (res.code === '200') {
          this.msgSuccess('清理成功')
        } else {
          this.msgError(res.msg)
        }
      })
    }
  }
}
</script>
